package com.goblin.model.uaa.controller;

import java.util.List;
import java.util.Optional;

import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.goblin.common.response.Response;
import com.goblin.model.base.BaseController;
import com.goblin.model.uaa.po.Menu;
import com.goblin.model.uaa.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1/uaa/menu")
public class MenuController extends BaseController<Menu> {

	@Autowired
	private MenuService menuService;

	@GetMapping("/menus")
	public Response<Paged<Menu>> paged(PageHelper pageable) {
		Paged<Menu> entities = this.menuService.paged(pageable);
		return Response.success(entities);
	}

	/**
	 * @desc: 获取菜单递归结构.
	 * @author goblin
	 * @date 2021/1/19 12:02
	 */
	@GetMapping("/tree")
	public Response<List<Menu>> tree() {
		List<Menu> entities = this.menuService.tree();
		return Response.success(entities);
	}

	@Override
	public <T> Object afterSave(T t) {
		super.afterSave(t);

		Menu m = (Menu) t;
		// 添加关联
		Optional<Menu> optional = this.menuService.findByParentId(m.getParentId());
		if (optional.isPresent()) {
			Menu menu = optional.get();
			List<Menu> list = menu.getChildren();
			list.add(m);
			menu.setChildren(list);
			this.menuService.save(menu);
		}
		return null;
	}
}
